//
//  String+Extension.swift
//  LiveTrivia
//
//  Created by Gesen on 2017/11/19.
//  Copyright © 2017年 LiveTrivia. All rights reserved.
//

import Foundation
import Kingfisher

extension String: Resource {
    
    public var cacheKey: String { return self }
    public var downloadURL: URL { return URL(string: self) ?? URL(string: "https://www.abc.com")! }
}

extension String {
    
    func contains(find: String) -> Bool {
        return range(of: find) != nil
    }
    
    func toURL() -> URL? {
        return URL(string: self)
    }

    func toDate(format: String = "yyyy-MM-dd HH:mm:ss.0") -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.date(from: self)
    }
    
    func toAttr(_ attributes: [NSAttributedString.Key: Any] = [:]) -> NSAttributedString {
        return NSAttributedString(string: self, attributes: attributes)
    }
    
    func isValidIP() -> Bool {
        let regex = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: self)
    }
    
    func isValidateEmail() -> Bool {
        let regex = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
        let predicate =  NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: self)
    }
    
    func isPhoneNumber() -> Bool {
        let regex = "^1[3,4,5,6,7,8,9]\\d{9}$"
        let predicate =  NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: self)
    }
    
    func isIDCard() -> Bool {
        let regex = "(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)"
        let predicate =  NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: uppercased())
    }
    
    func parseToArray() -> [String]? {
        guard let data = data(using: .utf8) else {
            return nil
        }
        guard let json = try? JSONSerialization.jsonObject(with: data) else {
            return nil
        }
        return json as? [String]
    }
    
    func encryptName() -> String {
        guard count != 0 else {
            return ""
        }
        var temp: String = ""
        for (i,c) in enumerated(){
            if i == count - 1{
                temp = "\(temp)\(c)"
            } else{
                 temp = "\(temp)*"
            }
        }
        return temp
    }
    
    func encryptEmail() -> String {
        guard count != 0 else {
            return ""
        }
        return "\(prefix(2))****\(suffix(2))"
    }
    
    func encryptPhone() -> String {
        guard count != 0 else {
            return ""
        }
        return "\(prefix(3))****\(suffix(4))"
    }
    
    func encryptCardID() -> String {
        guard count != 0 else {
            return ""
        }
        return "\(prefix(4))****\(suffix(4))"
    }
    
    /// string转attributedString，主要用于label计算高度时候
    func set(lineSpacing: CGFloat,
             alignment: NSTextAlignment = .left,
             lineBreakMode: NSLineBreakMode = .byTruncatingTail
        ) -> NSMutableAttributedString {
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = alignment
        paragraphStyle.lineSpacing = lineSpacing //大小调整
        paragraphStyle.lineBreakMode = lineBreakMode
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(.paragraphStyle,
                                      value: paragraphStyle,
                                      range: NSMakeRange(0, count))
        return attributedString
    }
    
    /// 改变字符串中数字的颜色和字体
    ///
    /// - Parameters:
    ///   - color: 颜色
    ///   - font: 字体
    ///   - regx: 正则 默认数字 "\\d+\\.?\\d*"
    /// - Returns: attributeString
    func numberRegxChange(color: UIColor,
                      font: UIFont) -> NSMutableAttributedString {
        return regxChange(color: color, font: font, regx: "\\d+\\.?\\d*")
    }
    
    func regxChange(color: UIColor,
                    font: UIFont,
                    regx: String) -> NSMutableAttributedString {
        let attributeString = NSMutableAttributedString(string: self)
        do {
            // 数字正则表达式
            let regexExpression = try NSRegularExpression(pattern: regx, options: NSRegularExpression.Options())
            let result = regexExpression.matches(
                in: self,
                options: NSRegularExpression.MatchingOptions(),
                range: NSMakeRange(0, count)
            )
            for item in result {
                attributeString.setAttributes(
                    [.foregroundColor : color, .font: font],
                    range: item.range
                )
            }
        } catch {
            print("Failed with error: \(error)")
        }
        return attributeString
    }
}

extension String {
    
    func birthToAge(_ dateFormat: String = "yyyy-MM-dd") -> Int? {
        guard let date = date(withFormat: dateFormat) else {
            return nil
        }
        return Date().year - date.year
    }
}

extension String {
    
    func decode<T: Decodable>() throws -> T {
        guard let data = data(using: .utf8) else {
            throw NSError(domain: "数据错误", code: 0)
        }
        return try JSONDecoder().decode(T.self, from: data)
    }
}

extension Optional where Wrapped == String {
    
    var count: Int {
        return self?.count ?? 0
    }
}

/// 中英文字符长度，中文占两字符
/// lengthOfBytes(using: .utf8) 中文是三字符，英文是一字符
extension String {
    func numberOfChars() -> Int {
        var number = 0
        
        guard self.count > 0 else {return 0}
        
        for i in 0...self.count - 1 {
            let c: unichar = (self as NSString).character(at: i)
            
            if (c >= 0x4E00) {
                number += 2
            }else {
                number += 1
            }
        }
        return number
    }
}
